<template> 
<view class="ai-chat-page">
    <Navbar title="AI节电" class="ai-chat-navbar"/>
    <scroll-view 
      class="chat-content" 
      scroll-y="true"
      :scroll-top="scrollTop"
      @scrolltoupper="handleScrollToUpper"
      :upper-threshold="50"
    >
  <!-- 下拉加载更多 -->
  <view v-if="isLoading" class="loading-more">
    <text>加载中...</text>
  </view>
  
     <view v-for="(msg, idx) in messages" :key="msg.id" :class="['chat-row', msg.role === 'user' ? 'right' : 'left']">
     <template v-if="msg.role === 'ai'">
       <image class="avatar" src="/static/img/dragon-avatar.png" mode="widthFix"/>
       <view class="bubble" @longpress="copyMessage(msg.text)">
         <text>{{ msg.text }}</text>
         <view v-if="shouldShowTime(msg, idx)" class="message-time">{{ formatTime(msg.timestamp) }}</view>
       </view>
     </template>
     <template v-else>
       <view class="bubble" @longpress="copyMessage(msg.text)">
         <text>{{ msg.text }}</text>
         <view v-if="shouldShowTime(msg, idx)" class="message-time">{{ formatTime(msg.timestamp) }}</view>
         <view v-if="msg.status === 'sending'" class="message-status">发送中...</view>
         <view v-else-if="msg.status === 'failed'" class="message-status failed">
           发送失败
           <text class="retry-btn" @click="retryMessage(msg)">重试</text>
         </view>
       </view>
       <image class="avatar" :src="userInfo.avatar" mode="widthFix"/>
     </template>
      </view>
 </scroll-view>
     <view class="chat-input-bar">
      <view class="input-group">
                 <input
           v-model="input"
           class="chat-input"
           placeholder="咨询节电小技巧..."
           @confirm="debouncedSend"
           confirm-type="send"
           :adjust-position="true"
           :cursor-spacing="20"
         />
       </view>
       <VoiceButton :currentValue="input" @update="handleVoiceInput" />
       <button class="send-btn" @click="debouncedSend">发送</button>
    </view>
</view>
</template>
<script setup>
import { ref, nextTick, onMounted, onUnmounted } from 'vue'
import Navbar from '@/components/Navbar.vue'
import VoiceButton from '@/components/VoiceButton.vue'
import { useGlobalStore } from '@/store/app'
import { useWebSocket } from '@/utils/websocket'
import { useDebounce } from '@/utils/useDebounce'
import { useThrottle } from '@/utils/useThrottle'
import config from '@/utils/config'

const store = useGlobalStore()
const userInfo = store.userInfo

// WebSocket相关
const { sendMessage, onMessage, offMessage, wsState } = useWebSocket()

// 聊天消息
const messages = ref([
  { 
    id: 'welcome-1',
    role: 'ai', 
    text: '您好，我是AI节电助手，有什么可以帮您？',
    timestamp: Date.now(),
    status: 'sent'
  }
])
const input = ref('')
const isLoading = ref(false)
const hasMore = ref(true)
const scrollTop = ref(0)
const messageIds = ref(new Set(['welcome-1'])) // 用于去重

// 发送消息函数定义
function send() {
  const text = input.value.trim()
  if (!text) return
  
  // 检查消息长度
  if (text.length > 400) {
    uni.showToast({
      title: '消息过长，请分段发送',
      icon: 'none',
      duration: 2000
    })
    return
  }
  
  // 检查连接状态
  if (!wsState.isConnected) {
    uni.showToast({
      title: '网络连接异常，请检查网络',
      icon: 'none',
      duration: 2000
    })
    return
  }
  
  // 生成唯一ID
  const messageId = `user-${Date.now()}-${Math.random().toString(36)}`
  
  const userMessage = {
    id: messageId,
    role: 'user',
    text,
    timestamp: Date.now(),
    status: 'sending'
  }
  
  messageIds.value.add(messageId)
  messages.value.push(userMessage)
  input.value = ''
  
  // 通过WebSocket发送消息
  const success = sendMessage('chat', {
    message: text,
  })
  
  if (success) {
    // 更新消息状态为已发送
    userMessage.status = 'sent'
  } else {
    // 发送失败
    userMessage.status = 'failed'
    uni.showToast({
      title: '发送失败，请重试',
      icon: 'none',
      duration: 2000
    })
  }
  
  throttledScrollToBottom()
}

// 滚动到底部函数定义
function scrollToBottom() {
  nextTick(() => {
    // 使用scroll-view的scroll-top属性滚动到底部
    // 设置一个很大的值来确保滚动到底部
    scrollTop.value = 999999
  })
}

// 防抖和节流处理
const debouncedSend = useDebounce(send, 600) // 发送消息防抖600ms (300+300)
const throttledScrollToBottom = useThrottle(scrollToBottom, 400) // 滚动节流400ms (100+300)

// 页面加载时注册消息处理器
onMounted(() => {
  // 注册聊天消息处理器
  onMessage('chat', handleChatMessage)
})

// 页面卸载时移除消息处理器
onUnmounted(() => {
  offMessage('chat', handleChatMessage)
})

// 处理收到的聊天消息
const handleChatMessage = (data) => {
  // 生成唯一ID
  const messageId = `ai-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
  
  // 检查是否重复消息
  if (messageIds.value.has(messageId)) {
    console.warn('收到重复消息，跳过')
    return
  }
  
  const newMessage = {
    id: messageId,
    role: 'ai',
    text: data.content || '收到消息',
    timestamp: Date.now(),
    status: 'sent'
  }
  
  messageIds.value.add(messageId)
  messages.value.push(newMessage)
  
  // 限制消息数量
  if (messages.value.length > config.chat.maxMessages) {
    const removedMessages = messages.value.splice(0, messages.value.length - config.chat.maxMessages)
    // 清理被移除消息的ID
    removedMessages.forEach(msg => messageIds.value.delete(msg.id))
  }
  
  throttledScrollToBottom()
}



// 下拉加载更多 - 使用uni-app的scroll-view事件
const handleScrollToUpper = useThrottle(() => {
  if (!isLoading.value && hasMore.value) {
    loadMoreMessages()
  }
}, 800) // 节流800ms，避免频繁触发 (500+300)

// 加载更多消息
const loadMoreMessages = () => {
  if (isLoading.value || !hasMore.value) return
  
  isLoading.value = true
  
  // 记录当前滚动位置
  const currentScrollTop = scrollTop.value
  
  // 模拟加载历史消息
  setTimeout(() => {
    const oldMessages = [
      {
        id: `history-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
        role: 'ai',
        text: '这是历史消息示例',
        timestamp: Date.now() - 86400000, // 1天前
        status: 'sent'
      }
    ]
    
    // 添加历史消息ID到去重集合
    oldMessages.forEach(msg => messageIds.value.add(msg.id))
    messages.value.unshift(...oldMessages)
    isLoading.value = false
    
    // 如果没有更多消息了
    if (messages.value.length > 50) {
      hasMore.value = false
    }
    
    // 保持滚动位置，避免跳动
    nextTick(() => {
      scrollTop.value = currentScrollTop + 100 // 稍微向下滚动一点
    })
  }, 1000)
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) { // 1天内
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return date.toLocaleDateString()
  }
}

// 判断是否显示时间
const shouldShowTime = (msg, idx) => {
  // 如果是第一条消息，显示时间
  if (idx === 0) return true
  
  // 获取上一条消息
  const prevMsg = messages.value[idx - 1]
  if (!prevMsg) return true
  
  // 如果上一条消息和当前消息时间差超过5分钟，显示时间
  const timeDiff = Math.abs(msg.timestamp - prevMsg.timestamp)
  return timeDiff > 5 * 60 * 1000 // 5分钟
}

// 处理输入事件 - 在uni-app中使用@confirm事件

// 重试发送失败的消息
const retryMessage = (message) => {
  // 检查连接状态
  if (!wsState.isConnected) {
    uni.showToast({
      title: '网络连接异常，请检查网络',
      icon: 'none',
      duration: 2000
    })
    return
  }
  
  message.status = 'sending'
  
  const success = sendMessage('chat', {
    content: message.text,
    userId: userInfo?.id || 'anonymous'
  })
  
  if (success) {
    message.status = 'sent'
  } else {
    message.status = 'failed'
    uni.showToast({
      title: '重试失败，请检查网络',
      icon: 'none',
      duration: 2000
    })
  }
}

// 复制消息到剪贴板
const copyMessage = (text) => {
  // #ifdef APP-PLUS
  uni.setClipboardData({
    data: text,
    success: () => {
      uni.showToast({
        title: '已复制到剪贴板',
        icon: 'success',
        duration: 1500
      })
    }
  })
  // #endif
}

// 语音输入回调
const handleVoiceInput = useDebounce((newValue) => {
  input.value = newValue
}, 400) // 防抖400ms，避免频繁更新输入框 (100+300)
</script>
<style scoped lang="scss">
.ai-chat-page {
  @include page-with-header;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: #172869;
}
.ai-chat-navbar {
  position: fixed !important;
  top: 1rpx;
  z-index: 10000;
}
.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 32rpx 24rpx 24rpx 24rpx;
  display: flex;
  flex-direction: column;
  gap: 32rpx;
  width: 100%;
  box-sizing: border-box;
}
.chat-row {
  display: flex;
  align-items: flex-start;
  width: 100%;
  margin-bottom: 18rpx;
}
.chat-row.left {
  justify-content: flex-start;
}
.chat-row.right {
  justify-content: flex-end;
}
.avatar {
  width: 80rpx;
  margin: 0 16rpx;
}
.bubble {
  max-width: 70%;
  min-width: 80rpx;
  padding: 20rpx 28rpx;
  border-radius: 24rpx;
  font-size: 28rpx;
  line-height: 1.6;
  word-break: break-all;
  background: #2E3D78;
  color: #ececec;
  margin: 0 8rpx;
  position: relative;
}

.message-time {
  font-size: 20rpx;
  color: #a0a0a0;
  margin-top: 8rpx;
  text-align: right;
}

.message-status {
  font-size: 20rpx;
  color: #ffa500;
  margin-top: 4rpx;
  text-align: right;
}

.message-status.failed {
  color: #ff4444;
}

.loading-more {
  text-align: center;
  padding: 20rpx;
  color: #a0a0a0;
  font-size: 24rpx;
}



.retry-btn {
  color: #1ec8e1;
  margin-left: 16rpx;
  text-decoration: underline;
  cursor: pointer;
}
.chat-row.left .bubble {

  border-top-left-radius: 8rpx;
}
.chat-row.right .bubble {

  border-top-right-radius: 8rpx;
}
.chat-input-bar {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background: #172869;
  position: sticky;
  bottom: 0;
  z-index: 10;
  gap: 12rpx;
}
.input-group {
  display: flex;
  align-items: center;
  background: #2E3D78;
  border-radius: 32rpx;
  padding: 0 16rpx;
  flex: 1;
}
.chat-input {
  flex: 1;
  height: 64rpx;
  border: none;
  background: transparent;
  font-size: 28rpx;
  color: #fff;
  margin-right: 8rpx;
}
.chat-input::placeholder {
  color: #a0a0a0;
}

/* 语音按钮样式 */
:deep(.voice-button-wrapper) {
  width: 56rpx;
  height: 56rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}



:deep(.voice-icon) {
  width: 24rpx;
  height: 24rpx;
  opacity: 0; /* 隐藏原来的图片 */
}

:deep(.voice-btn) {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  background: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  padding: 0;
  position: relative;
}

:deep(.voice-btn)::before {
  content: '';
  position: absolute;
  width: 56rpx;
  height: 56rpx;
  background-image: url('/static/img/consolePages/speech.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
}

:deep(.voice-text) {
  display: none !important;
}

.send-btn {
  background: linear-gradient(90deg, #1ec8e1 0%, #5ebeff 100%);
  color: #fff;
  border: none;
  border-radius: 32rpx;
  padding: 0 32rpx;
  height: 64rpx;
  font-size: 28rpx;
  font-weight: bold;
}
</style>